<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :title="title"
    :visible="visible"
    :width="1200"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="昵称"
            >
              <a-input
                :disabled="showable"
                placeholder="没有要求必填"
                v-decorator="['nickname', {initialValue: '初始化昵称'}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="用户名"
            >
              <a-input
                :disabled="showable"
                placeholder="必填项"
                v-decorator="['username', {rules: [{required: true, message: '请输入用户名'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="性别"
            >
              <a-select
                :disabled="showable"
                placeholder="请选择性别"
                v-decorator="['gender', {rules: [{required: true, message: '请选择性别'}]}]">
                <a-select-option value="1">男性</a-select-option>
                <a-select-option value="2">女性</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="身份证号码"
            >
              <a-input
                :disabled="showable"
                placeholder="请输入身份证号码"
                v-decorator="['idcard', validatorRules.idcard]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="手机号"
            >
              <a-input
                :disabled="showable"
                placeholder="请输入手机号，自定义验证"
                v-decorator="[ 'telphone', validatorRules.telphone]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="密码"
            >
              <a-input
                :disabled="showable"
                placeholder="请输入登陆密码"
                type="password"
                v-decorator="[ 'password', validatorRules.password]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="年龄"
            >
              <a-input-number
                :disabled="showable"
                placeholder="请输入年龄"
                style="width: 100%"
                v-decorator="['age', validatorRules.age]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="JSON"
            >
              <a-input
                :disabled="showable"
                placeholder="请输入JSON数组"
                v-decorator="['json', validatorRules.ruleParams]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="开始时间"
            >
              <a-date-picker
                :disabled="showable"
                style="width: 100%"
                v-decorator="['startTime', validatorRules.startTime]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="结束时间"
            >
              <a-date-picker
                :disabled="showable"
                style="width: 100%"
                v-decorator="['endTime', validatorRules.endTime]"/>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="描述"
            >
              <a-textarea
                :disabled="showable"
                :rows="4"
                placeholder="长度不超过 12 个字符"
                v-decorator="['description', validatorRules.description]"/>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>
    <template slot="footer">
      <div v-show="editable || addable">
        <a-button @click="handleCancel" key="cancel">取消</a-button>
        <a-button :loading="confirmLoading" @click="handleOk" key="forward" type="primary">保存</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { FormMixin } from '@/mixins/FormMixin'
import pick from 'lodash.pick'

export default {
  name: 'OrdinarySelectBox',
  mixins: [FormMixin],
  data () {
    return {
      moment,
      form: this.$form.createForm(this),
      confirmLoading: false,
      validatorRules: {
        telphone: {
          rules: [{
            required: true,
            pattern: /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/,
            message: '请输入正确的手机号!'
          }]
        },
        idcard: {
          rules: [{
            required: true,
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '请输入身份证号!'
          }]
        },
        password: {
          rules: [{
            required: true,
            pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: '密码由8位数字、大小写字母和特殊符号组成!'
          }]
        },
        age: {
          rules: [{
            required: true,
            pattern: /^200$|^(\d|[1-9]\d)$/,
            message: '年龄必须在0-200之间!'
          }]
        },
        startTime: {
          rules: [
            { required: true, message: '请选择开始时间!' },
            { validator: this.startTimeValidate }
          ]
        },
        endTime: {
          rules: [
            { required: true, message: '请选择结束时间!' },
            { validator: this.endTimeValidate }
          ]
        },
        description: {
          rules: [
            { required: true, message: '请输入描述!' },
            { min: 0, max: 12, message: '长度不超过 12 个字符', trigger: 'blur' }
          ]
        },
        ruleParams: {
          rules: [{
            validator: (rule, value, callback) => {
              try {
                const json = JSON.parse(value)
                if (json instanceof Array) {
                  callback(new Error('只能传递JSON对象，不能传递JSON数组'))
                } else if (json instanceof Object) {
                  callback()
                } else {
                  callback(new Error('请输入JSON字符串'))
                }
              } catch {
                callback(new Error('请输入JSON字符串'))
              }
            }
          }]
        }
      }
    }
  },
  methods: {
    edit (id, type) {
      this.visible = true
      const { form: { setFieldsValue, resetFields } } = this
      if (['edit', 'show'].includes(type)) {
        this.confirmLoading = true
        setTimeout(() => {
          const record = {
            username: '测试用户名',
            gender: '1',
            idcard: '370724199901230313',
            telphone: '18263658149',
            password: 'asd123!@#',
            age: '18',
            json: '{}',
            startTime: '2019-01-01',
            endTime: '2019-01-10',
            description: '测试描述'
          }
          record.startTime = moment(record.startTime)
          record.endTime = moment(record.endTime)
          this.confirmLoading = false
          this.$nextTick(() => {
            setFieldsValue(pick(record, ['username', 'gender', 'idcard', 'telphone', 'password', 'age', 'json', 'startTime', 'endTime', 'description']))
          }, 2000)
        })
      } else {
        resetFields()
      }
    },
    handleOk () {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.$message.info(JSON.stringify(values))
        }
      })
    },
    // -------------------------------------check--start
    startTimeValidate (rule, value, callback) {
      const endTime = this.form.getFieldValue('endTime')
      if (!value || !endTime) {
        callback()
      } else if (moment(value).isBefore(endTime)) {
        callback()
      } else {
        callback(new Error('开始时间需小于结束时间'))
      }
    },
    endTimeValidate (rule, value, callback) {
      const startTime = this.form.getFieldValue('startTime')
      if (!value || !startTime) {
        callback()
      } else if (moment(startTime).isBefore(value)) {
        callback()
      } else {
        callback(new Error('结束时间需大于开始时间'))
      }
    }
    // -------------------------------------check--end
  }
}
</script>

<style scoped>
</style>
